<?php
/**
 * 股票类，用于读取和写入股票的买入、止盈、止损价格
 * @author 王志昂<wangzhiang@myhexin.com>
 * @create 2013-4-23 20:23:56
 */
class Subscribe_Push_Stock
{
	public function setAlertStock(array $stockInfo)
	{
		$table = Dzl_Db_Factory::getInstance()->createTable('dzl_alert_stocks');
		
		try {
			$time = date('Y-m-d H:i:s');
			$base = array(
				'ctime' => $time,
				'mtime' => $time,
				'alive' => 1
			);
			$binds = array_merge($base, $stockInfo);
			
			$rtn = $table->insert($binds);
			if (!$rtn) {
				return array(
					'errorcode' => -1,
					'errormsg' => 'insert failed!'
				);
			}
		} catch (Zend_Exception $e) {
			return array(
				'errorcode' => -2,
				'errormsg' => $e->getMessage()
			);
		}
		return array(
			'errorcode' => 0,
			'errormsg' => 'success'
		);
	}
	
	public function getAllAlertStock($style = null)
	{
		$stmt = Dzl_Db_Factory::getInstance()
			->createSelect()
			->from('dzl_alert_stocks', '*')
			->where('alive=?', 1);
		if ($style !== null) {
			$stmt->where('style=?', $style);
		}
		$rtn = $stmt->query()->fetchAll();
		return $rtn;
	}
	
	public function updateAlertStock(array $stockInfo)
	{
		$time = date('Y-m-d H:i:s');
		$base = array(
			'mtime' => $time,
		);
		$binds = array_merge($base, $stockInfo);
		$where = array(
			'id=?' => $stockInfo['id']
		);
		$rtn = Dzl_Db_Factory::getInstance()
			->createTable('dzl_alert_stocks')
			->update($binds, $where);
		
		return $rtn ? true : false;
	}
	
	public function getCurrentPrice($code)
	{
		$hqBaseUrl = Zend_Registry::get('dzlalert')->hq->url;
		$requestUrl = $hqBaseUrl . '?method=quote' . '&code=' . $code . '&datatype=new' . '&datetime=0(0-0)';
		$content = file_get_contents($requestUrl);
		$contentArr = json_decode($content, true);
		if ($contentArr['error'] === null) {
			$price = $contentArr['result']['data'][0]['table'][0][10];
		} else {
			$price = 0;
		}
		return $price;
	}
}